package com.cxf.windex.base.util;

import com.cxf.windex.entity.vo.WxInfo;
import com.cxf.windex.entity.vo.WxPayInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 微信支付
 *
 * @author chenxf
 * @version 1.0
 * @date 2019-01-28 19:45
 **/
public class WxPayUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(WxPayUtil.class);
    private static String appId="wx9940ad98b7e29dea";
    private static String appKey = "W8Sjj09xsiesYE72ipq9SnbuN88Svx02";
    private static String secret="bf72f90df6c5c9cb753d07f0506f6e34";
    private static String mchId="1525014841";
    private static String wxOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private static String timeformat = "yyyyMMddHHmmss";
    private static int timeexpire = 1;

    /**
     * 统一下单接口
     * @param clientIP 客户端IP
     * @param randomNonceStr 随机数
     * @param appid appid
     * @param mchid 商户号
     * @param notifyUrl 回调地址
     * @param appKey 商户密钥
     */
    public static String unifiedOrder( String clientIP, String randomNonceStr,
                                      String appid, String mchid, String notifyUrl, String appKey) {
        try {
            WxInfo payInfo = new WxInfo()
                    .createInfo( clientIP, randomNonceStr, timeformat, timeexpire, appid, mchid,
                            notifyUrl);
            String md5 = getSign(payInfo, appKey);
            payInfo.setSign(md5);

            logger.error("md5 value: " + md5);

            String xml = CommonUtil.payInfoToXML(payInfo);
            xml = xml.replace("__", "_").replace("<![CDATA[1]]>", "1");
            //xml = xml.replace("__", "_").replace("<![CDATA[", "").replace("]]>", "");
            logger.info("xml={}", xml);
            StringBuffer buffer = HttpUtil.httpsRequest(wxOrderUrl, "POST", xml);

            logger.error("unifiedOrder request return body: \n" + buffer.toString());
            Map<String, String> result = CommonUtil.parseXml(buffer.toString());

            String return_code = result.get("return_code");
            if (StringUtils.isNotBlank(return_code) && return_code.equals("SUCCESS")) {

                String return_msg = result.get("return_msg");
                if (StringUtils.isNotBlank(return_msg) && !return_msg.equals("OK")) {
                    return "";
                }

                String prepay_Id = result.get("prepay_id");
                return prepay_Id;

            } else {
                return "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private static String getSign(WxInfo payInfo, String key) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("appid=" + payInfo.getAppid())
               // .append("&attach=" + payInfo.getAttach())
                .append("&body=" + payInfo.getBody())
               // .append("&device_info=" + payInfo.getDevice_info())
               // .append("&limit_pay=" + payInfo.getLimit_pay())
                .append("&mch_id=" + payInfo.getMch_id())
                .append("&nonce_str=" + payInfo.getNonce_str())
                .append("&notify_url=" + payInfo.getNotify_url())
                .append("&out_trade_no=" + payInfo.getOut_trade_no())
               // .append("&sign_type=" + payInfo.getSign_type())
               .append("&spbill_create_ip=" + payInfo.getSpbill_create_ip())
              //  .append("&time_expire=" + payInfo.getTime_expire())
              //  .append("&time_start=" + payInfo.getTime_start())
                .append("&total_fee=" + payInfo.getTotal_fee())
                .append("&trade_type=" + payInfo.getTrade_type())
                .append("&key=" + key);
        logger.info("url={}",sb.toString());
        return CommonUtil.getMD5(sb.toString().trim()).toUpperCase();
    }



    public static void main(String[] args){        WxPayUtil.unifiedOrder("123.152.222.94", RandomUtils.generateString(32),appId,mchId,"http://www.baidu.com",appKey);

    }
}
